<template>
  <div class="club-browse">
    <div class="search-section">
      <el-form :model="searchForm" label-width="80px" class="search-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="社团名称">
              <el-input 
                v-model="searchForm.clubName" 
                placeholder="请输入社团名称" 
                clearable
                @keyup.enter="searchClubs"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="社团类型">
              <el-select v-model="searchForm.clubType" placeholder="请选择类型" clearable style="width: 100%">
                <el-option label="学术科技类" value="1" />
                <el-option label="文化艺术类" value="2" />
                <el-option label="体育运动类" value="3" />
                <el-option label="社会实践类" value="4" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="招新状态">
              <el-select v-model="searchForm.recruitmentStatus" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="招新中" value="1" />
                <el-option label="未开始" value="0" />
                <el-option label="已结束" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" @click="searchClubs">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    
    <div v-loading="loading">
      <div v-if="!searchForm.clubName && !searchForm.clubType && !searchForm.recruitmentStatus" class="popular-clubs">
        <h3>热门社团推荐</h3>
        <el-row :gutter="20">
          <el-col :span="6" v-for="club in popularClubs" :key="club.clubId">
            <div class="club-card popular" @click="viewClubDetails(club)">
              <div class="club-logo">
                <img :src="club.logoUrl || '/default-club.png'" :alt="club.clubName" />
              </div>
              <div class="club-info">
                <h4>{{ club.clubName }}</h4>
                <p class="club-type">{{ getClubTypeName(club.clubType) }}</p>
                <p class="club-members">{{ club.memberCount || 0 }} 人</p>
                <el-tag 
                  :type="getRecruitmentStatusType(club.status || club.recruitmentStatus)" 
                  size="small"
                >
                  {{ getRecruitmentStatusText(club.status || club.recruitmentStatus) }}
                </el-tag>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      
      <div class="clubs-list">
        <h3>{{ searchForm.clubName || searchForm.clubType || searchForm.recruitmentStatus ? '搜索结果' : '所有社团' }}</h3>
        <el-row :gutter="20">
          <el-col :span="8" v-for="club in clubs" :key="club.clubId">
            <div class="club-card" @click="viewClubDetails(club)">
              <div class="club-logo">
                <img :src="club.logoUrl || '/default-club.png'" :alt="club.clubName" />
              </div>
              <div class="club-info">
                <h4>{{ club.clubName }}</h4>
                <p class="club-type">{{ getClubTypeName(club.clubType) }}</p>
                <p class="club-description">{{ club.description || '暂无简介' }}</p>
                <div class="club-stats">
                  <span><el-icon><User /></el-icon> {{ club.memberCount || 0 }} 人</span>
                  <span><el-icon><Document /></el-icon> {{ club.recruitmentCount || 0 }} 个职位</span>
                </div>
                <div class="club-actions">
                  <el-tag 
                    :type="getRecruitmentStatusType(club.status || club.recruitmentStatus)" 
                    size="small"
                  >
                    {{ getRecruitmentStatusText(club.status || club.recruitmentStatus) }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        
        <div v-if="total > 0" class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.pageNum"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[9, 18, 36]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>
    
    <!-- 社团详情对话框 -->
    <el-dialog 
      v-model="detailVisible" 
      :title="selectedClub && selectedClub.clubName ? selectedClub.clubName : '社团详情'" 
      width="800px"
      class="club-detail-dialog"
    >
      <div v-if="selectedClub" class="club-detail">
        <el-row :gutter="20">
          <el-col :span="8">
            <div class="club-detail-logo">
              <img :src="selectedClub.logoUrl || '/default-club.png'" :alt="selectedClub.clubName" />
            </div>
          </el-col>
          <el-col :span="16">
            <div class="club-detail-info">
              <h3>{{ selectedClub.clubName }}</h3>
              <p><strong>社团类型：</strong>{{ getClubTypeName(selectedClub.clubType) }}</p>
              <p><strong>成立时间：</strong>{{ formatDate(selectedClub.createTime) }}</p>
              <p><strong>社团规模：</strong>{{ selectedClub.memberCount || 0 }} 人</p>
              <p><strong>社团简介：</strong>{{ selectedClub.description || '暂无简介' }}</p>
            </div>
          </el-col>
        </el-row>
        
        <!-- 招新职位部分 -->
        <div v-if="selectedRecruitments.length > 0" class="recruitments-section">
          <h4>招新职位</h4>
          <div v-for="rec in selectedRecruitments" :key="rec.recruitmentId" class="recruitment-item">
            <div class="rec-header">
              <h5>{{ rec.title || rec.positionName }}</h5>
              <el-tag :type="getRecruitmentStatusType(rec.status || rec.recruitmentStatus)">{{ getRecruitmentStatusText(rec.status || rec.recruitmentStatus) }}</el-tag>
            </div>
            <div class="rec-content">
              <p><strong>招聘人数：</strong>{{ rec.recruitCount || '若干' }} 人</p>
              <p><strong>报名截止：</strong>{{ formatDate(rec.deadline) }}</p>
              <p><strong>职位要求：</strong>{{ rec.requirements || '无特殊要求' }}</p>
              <p><strong>工作内容：</strong>{{ rec.description || '暂无描述' }}</p>
            </div>
            <div class="rec-actions">
              <el-button 
                type="primary" 
                @click="applyForRecruitment(rec)"
                :disabled="rec.status === 2 || rec.recruitmentStatus === 2"
              >
                立即申请
              </el-button>
              <!-- <div class="debug-info">
                UserID: {{ getValidUserId.value }}, Status: {{ rec.status || rec.recruitmentStatus }}
              </div> -->
            </div>
          </div>
        </div>
        
        <div v-else class="recruitments-section">
          <el-empty description="暂无招新职位" />
        </div>
      </div>
      
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 申请表单对话框 -->
    <el-dialog 
      v-model="applyVisible" 
      title="申请加入社团" 
      width="600px"
    >
      <el-form ref="applyFormRef" :model="applyForm" :rules="applyRules" label-width="100px">
        <el-form-item label="申请社团" prop="clubName">
          <el-input v-model="applyForm.clubName" disabled />
        </el-form-item>
        <el-form-item label="申请岗位" prop="recruitmentTitle">
          <el-input v-model="applyForm.recruitmentTitle" disabled />
        </el-form-item>
        <el-form-item label="个人简介" prop="personalIntroduction">
          <el-input v-model="applyForm.personalIntroduction" type="textarea" :rows="4" placeholder="请简要介绍自己的基本情况、兴趣特长等" />
        </el-form-item>
        <el-form-item label="申请理由" prop="applicationReason">
          <el-input v-model="applyForm.applicationReason" type="textarea" :rows="3" placeholder="请说明为什么想加入该社团和申请该职位" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="applyForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="applyVisible = false">取消</el-button>
        <el-button type="primary" @click="submitApplication" :loading="submitting">提交申请</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { User, Document } from '@element-plus/icons-vue'
import { listClub, getClub, getPopularClubs, listRecruitment, getRecruitment, apiSubmitApplication } from '@/api/campus/student/clubBrowse'
import useUserStore from '@/store/modules/user'

const emit = defineEmits(['switch-to-applications', 'apply-for-recruitment'])

// Props
const props = defineProps({
  currentUserId: {
    type: String,
    required: false,
    default: ''
  }
})

// Data
const loading = ref(false)
const detailVisible = ref(false)
const applyVisible = ref(false)
const submitting = ref(false)
const clubs = ref([])
const popularClubs = ref([])
const selectedClub = ref(null)
const selectedRecruitments = ref([])
const selectedRecruitment = ref(null)
const total = ref(0)
const applyFormRef = ref(null)

const searchForm = reactive({
  clubName: '',
  clubType: '',
  recruitmentStatus: '',
  pageNum: 1,
  pageSize: 9
})

// 申请表单数据
const applyForm = reactive({
  clubName: '',
  recruitmentTitle: '',
  personalIntroduction: '',
  applicationReason: '',
  phone: ''
})

// 申请表单验证规则
const applyRules = reactive({
  personalIntroduction: [
    { required: true, message: '请输入个人简介', trigger: 'blur' },
    { min: 10, max: 500, message: '个人简介长度应在10-500个字符之间', trigger: 'blur' }
  ],
  applicationReason: [
    { required: true, message: '请输入申请理由', trigger: 'blur' },
    { min: 10, max: 300, message: '申请理由长度应在10-300个字符之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 从多个可能的位置获取用户ID的辅助函数
const getUserIdFromStorage = () => {
  // 打印所有localStorage键值对，调试用
  console.log('===== localStorage 内容分析 =====');
  for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    try {
      const value = localStorage.getItem(key);
      console.log(`localStorage[${key}]:`, value);
      
      // 特别检查用户相关的关键字段
      if (key.toLowerCase().includes('user') || 
          key.toLowerCase().includes('token') || 
          key.toLowerCase().includes('auth')) {
        console.log(`🚨 可能包含用户信息的字段: ${key}`);
        // 尝试解析为对象
        try {
          const parsed = JSON.parse(value);
          console.log(`解析后内容:`, parsed);
        } catch (e) {
          console.log(`不是JSON格式`);
        }
      }
    } catch (e) {
      console.log(`读取 ${key} 时出错:`, e);
    }
  }
  console.log('==================================');

  // 尝试从所有可能的位置获取用户ID
  let userId = '';
  
  // 1. 尝试从常见的用户ID字段获取
  const userIdKeys = ['userId', 'id', 'user_id', 'username', 'loginName', 'account'];
  for (const key of userIdKeys) {
    const value = localStorage.getItem(key);
    if (value && value.trim()) {
      userId = value;
      console.log(`1. 从 ${key} 获取到用户ID:`, userId);
      break;
    }
  }
  
  // 2. 尝试从userInfo对象中获取各种可能的用户ID字段
  if (!userId) {
    try {
      const userInfoStr = localStorage.getItem('userInfo') || localStorage.getItem('userinfo');
      if (userInfoStr) {
        const userInfo = JSON.parse(userInfoStr);
        console.log('发现userInfo对象:', userInfo);
        
        // 尝试所有可能的用户ID字段名
        const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'studentId'];
        for (const field of possibleIdFields) {
          if (userInfo[field] && String(userInfo[field]).trim()) {
            userId = String(userInfo[field]);
            console.log(`2. 从userInfo.${field}获取到用户ID:`, userId);
            break;
          }
        }
      }
    } catch (e) {
      console.warn('解析userInfo失败:', e);
    }
  }
  
  // 3. 尝试从token或其他认证信息中获取
  if (!userId) {
    try {
      const tokenKeys = ['token', 'Authorization', 'auth_token', 'access_token'];
      let token = '';
      
      for (const key of tokenKeys) {
        token = localStorage.getItem(key);
        if (token) break;
      }
      
      if (token) {
        console.log('发现token:', token);
        // 简单尝试解码token前半部分
        try {
          const tokenParts = token.split('.');
          if (tokenParts.length >= 2) {
            const decoded = JSON.parse(atob(tokenParts[1].replace(/-/g, '+').replace(/_/g, '/')));
            console.log('token解码内容:', decoded);
            
            // 尝试所有可能的用户ID字段名
            const possibleIdFields = ['id', 'userId', 'user_id', 'username', 'loginName', 'account', 'sub', 'name'];
            for (const field of possibleIdFields) {
              if (decoded[field] && String(decoded[field]).trim()) {
                userId = String(decoded[field]);
                console.log(`3. 从token.${field}获取到用户ID:`, userId);
                break;
              }
            }
          }
        } catch (e) {
          console.warn('解码token失败:', e);
        }
      }
    } catch (e) {
      console.warn('从token获取用户ID失败:', e);
    }
  }
  
  return userId;
};

// 获取有效的用户ID（优先使用store，其次是props，最后是localStorage）
const getValidUserId = computed(() => {
  // 1. 从store获取用户ID（最高优先级）
  try {
    const userStore = useUserStore();
    if (userStore && userStore.id) {
      console.log('从store获取到用户ID:', userStore.id);
      return String(userStore.id).trim();
    }
  } catch (error) {
    console.warn('获取store用户信息失败:', error);
  }
  
  // 2. 从props获取userId
  const userIdFromProps = String(props.currentUserId || '').trim();
  console.log('props中的用户ID:', userIdFromProps);
  
  // 3. 检查localStorage中的userId
  const userIdFromStorage = getUserIdFromStorage();
  const validUserId = userIdFromProps || userIdFromStorage;
  
  console.log('最终有效用户ID:', validUserId);
  return validUserId;
});

// 判断用户是否已登录
const isUserLoggedIn = computed(() => {
  const validUserId = getValidUserId.value;
  return validUserId && validUserId !== 'undefined' && validUserId !== 'null' && validUserId.trim() !== '';
});

// Methods
const loadClubs = async () => {
  loading.value = true;
  const params = { ...searchForm };
  if (params.recruitmentStatus === '') delete params.recruitmentStatus;
  if (params.clubType === '') delete params.clubType;
  if (params.clubName === '') delete params.clubName;
  
  try {
    const response = await listClub(params);
    if (response.code === 200) {
      clubs.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      ElMessage.error('获取社团列表失败: ' + (response.msg || '未知错误'));
      clubs.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('加载社团列表失败:', error);
    ElMessage.error('网络错误，请稍后重试');
    clubs.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
}

const loadPopularClubs = async () => {
  try {
    const response = await getPopularClubs();
    if (response.code === 200) {
      popularClubs.value = (response.data || []).slice(0, 4);
    } else {
      popularClubs.value = [];
    }
  } catch (error) {
    console.error('加载热门社团失败:', error);
    popularClubs.value = [];
  }
}

const searchClubs = () => {
  searchForm.pageNum = 1;
  loadClubs();
}

const resetSearch = () => {
  searchForm.clubName = '';
  searchForm.clubType = '';
  searchForm.recruitmentStatus = '';
  searchForm.pageNum = 1;
  loadClubs();
}

const handleSizeChange = (val) => {
  searchForm.pageSize = val;
  searchForm.pageNum = 1;
  loadClubs();
}

const handleCurrentChange = (val) => {
  searchForm.pageNum = val;
  loadClubs();
}

const viewClubDetails = async (club) => {
  try {
    // 获取社团详细信息
    const clubResponse = await getClub(club.clubId);
    if (clubResponse.code === 200) {
      selectedClub.value = clubResponse.data || club;
    } else {
      selectedClub.value = club;
    }
    
    // 获取该社团的招新职位
    const recruitmentResponse = await listRecruitment({ clubId: club.clubId });
    if (recruitmentResponse.code === 200) {
      selectedRecruitments.value = recruitmentResponse.rows || [];
    } else {
      selectedRecruitments.value = [];
    }
    
    detailVisible.value = true;
  } catch (error) {
    console.error('获取社团详情失败:', error);
    ElMessage.error('网络错误，请稍后重试');
  }
}

const applyForRecruitment = (recruitment) => {
  // 检查用户是否已登录
  if (!isUserLoggedIn.value) {
    ElMessage.warning('请先登录后再申请');
    return;
  }
  
  // 设置申请表单数据
  applyForm.clubName = selectedClub.value.clubName;
  applyForm.recruitmentTitle = recruitment.title || recruitment.positionName;
  applyForm.personalIntroduction = '';
  applyForm.applicationReason = '';
  applyForm.phone = '';
  
  // 保存选中的招聘信息
  selectedRecruitment.value = recruitment;
  
  // 打开申请表单对话框
  applyVisible.value = true;
}

const submitApplication = async () => {
  // 验证表单
  if (!applyFormRef.value) {
    ElMessage.warning('表单引用未初始化');
    return;
  }
  
  try {
    await applyFormRef.value.validate();
  } catch (error) {
    ElMessage.warning('请检查表单填写是否正确');
    return;
  }
  
  // 确保提交申请时包含用户ID
  const validUserId = getValidUserId.value;
  
  if (!validUserId || validUserId === 'undefined' || validUserId === 'null' || validUserId.trim() === '') {
    ElMessage.warning('用户未登录，请先登录');
    return;
  }
  
  // 检查selectedClub和selectedRecruitment是否存在
  if (!selectedClub.value || !selectedRecruitment.value) {
    ElMessage.warning('请选择要申请的社团和岗位');
    return;
  }
  
  // 安全地获取必要字段，使用更严格的空值处理
  const safeGet = (obj, path, defaultValue = '') => {
    if (!obj || typeof obj !== 'object') return defaultValue;
    
    const parts = path.split('.');
    let result = obj;
    
    for (const part of parts) {
      if (result === null || result === undefined || !Object.hasOwnProperty.call(result, part)) {
        return defaultValue;
      }
      result = result[part];
    }
    
    return result === null || result === undefined ? defaultValue : result;
  };
  
  // 使用safeGet函数获取字段，确保不会出现空指针
  const recruitmentId = String(safeGet(selectedRecruitment.value, 'recruitmentId', ''));
  const clubId = String(safeGet(selectedClub.value, 'clubId', ''));
  const clubName = String(safeGet(selectedClub.value, 'clubName', ''));
  const positionName = String(
    safeGet(selectedRecruitment.value, 'positionName', '') || 
    safeGet(selectedRecruitment.value, 'title', '') || 
    safeGet(selectedRecruitment.value, 'recruitmentTitle', '')
  );
  
  // 验证关键字段是否有有效内容
  if (!recruitmentId || recruitmentId === 'undefined' || recruitmentId === 'null' || recruitmentId.trim() === '') {
    ElMessage.warning('缺少有效的岗位信息，请重新选择');
    console.error('无效的recruitmentId:', recruitmentId);
    return;
  }
  
  if (!clubId || clubId === 'undefined' || clubId === 'null' || clubId.trim() === '') {
    ElMessage.warning('缺少有效的社团信息，请重新选择');
    console.error('无效的clubId:', clubId);
    return;
  }
  
  // 创建符合后端API期望的数据对象
  // 根据CrApplicationController要求：需要studentId、recruitmentId和applicationContent字段
  const personalIntroduction = String(applyForm.personalIntroduction || '');
  const applicationReason = String(applyForm.applicationReason || '');
  const phone = String(applyForm.phone || '');
  
  // 将多个字段合并为一个applicationContent字段，按照后端期望的格式
  const applicationContent = `个人简介：${personalIntroduction}\n\n申请理由：${applicationReason}\n\n联系电话：${phone}`;
  
  const applicationData = {
    studentId: validUserId, // 使用studentId而不是userId
    recruitmentId: recruitmentId,
    applicationContent: applicationContent
  };
  
  // 最终清理，确保所有字段都不为null或undefined且都是字符串类型
  Object.keys(applicationData).forEach(key => {
    if (applicationData[key] === null || applicationData[key] === undefined) {
      applicationData[key] = '';
    } else {
      applicationData[key] = String(applicationData[key]);
    }
  });
  
  console.log('提交申请数据:', JSON.stringify(applicationData));
  
  submitting.value = true;
  try {
    // 再次验证数据完整性
    console.log('数据验证检查:', {
      userId: !!applicationData.userId,
      recruitmentId: !!applicationData.recruitmentId,
      clubId: !!applicationData.clubId,
      dataTypes: Object.entries(applicationData).reduce((acc, [key, value]) => {
        acc[key] = typeof value;
        return acc;
      }, {})
    });
    
    const response = await apiSubmitApplication(applicationData);
    if (response && response.code === 200) {
      ElMessage.success('申请提交成功');
      applyVisible.value = false;
      emit('switch-to-applications');
    } else {
      const errorMsg = response && response.msg ? response.msg : '提交失败: 未收到正确的响应';
      ElMessage.error(errorMsg);
      console.error('API返回错误:', response);
    }
  } catch (error) {
    console.error('提交申请失败 - 异常详情:', error);
    console.error('提交申请失败 - 数据检查:', {
      userId: applicationData.userId,
      recruitmentId: applicationData.recruitmentId,
      clubId: applicationData.clubId,
      allData: applicationData
    });
    
    // 提供更友好的错误提示
    let userFriendlyError = '提交申请失败，请稍后重试';
    if (error.message && error.message.includes('null')) {
      userFriendlyError = '数据格式问题，请检查输入并确保所有必填项都已填写';
    }
    ElMessage.error(userFriendlyError);
  } finally {
    submitting.value = false;
  }
}

const handleApplyFromRecommendation = (recommendation) => {
  // 检查用户是否已登录
  if (!isUserLoggedIn.value) {
    ElMessage.warning('请先登录后再申请');
    return;
  }
  
  // 这里可以根据推荐信息直接打开申请表单，或者先加载社团详情
  const club = {
    clubId: recommendation.clubId,
    clubName: recommendation.clubName
  };
  
  const recruitment = {
    recruitmentId: recommendation.recruitmentId,
    title: recommendation.recruitmentTitle
  };
  
  // 设置选中的社团和招聘信息
  selectedClub.value = club;
  selectedRecruitment.value = recruitment;
  
  // 设置申请表单数据
  applyForm.clubName = club.clubName;
  applyForm.recruitmentTitle = recruitment.title;
  applyForm.personalIntroduction = '';
  applyForm.applicationReason = '';
  applyForm.phone = '';
  
  // 打开申请表单对话框
  applyVisible.value = true;
}

// Utility functions
const getClubTypeName = (type) => {
  const typeStr = type !== null && type !== undefined ? String(type) : '';
  const map = { '1': '学术科技类', '2': '文化艺术类', '3': '体育运动类', '4': '社会实践类' };
  return map[typeStr] || '未知类型';
}

const getRecruitmentStatusText = (status) => {
  const statusStr = status !== null && status !== undefined ? String(status) : '';
  const map = { '0': '招聘中', '1': '已暂停', '2': '已结束' };
  return map[statusStr] || '未知状态';
}

const getRecruitmentStatusType = (status) => {
  const statusStr = status !== null && status !== undefined ? String(status) : '';
  const map = { '0': 'success', '1': 'warning', '2': 'danger' };
  return map[statusStr] || 'info';
}

const formatDate = (date) => {
  if (!date) return '未知';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  const hours = String(d.getHours()).padStart(2, '0');
  const minutes = String(d.getMinutes()).padStart(2, '0');
  const seconds = String(d.getSeconds()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 监听localStorage变化
const handleStorageChange = () => {
  // 当localStorage中的用户ID变化时，重新检查登录状态
  console.log('监听到localStorage变化，检查登录状态:', isUserLoggedIn());
}

// Initialize
onMounted(() => {
  loadClubs();
  loadPopularClubs();
  
  // 添加localStorage监听
  window.addEventListener('storage', handleStorageChange);
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  window.removeEventListener('storage', handleStorageChange);
});

// Expose methods for parent component
defineExpose({
  handleApplyFromRecommendation
})
</script>

<style scoped>
.club-browse {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.search-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0,0,0,0.1);
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.popular-clubs h3,
.clubs-list h3 {
  margin: 0 0 16px;
  color: #303133;
}

.club-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  cursor: pointer;
  transition: all 0.3s ease;
}

.club-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.15);
}

.club-card.popular {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.club-card.popular h4 {
  color: white;
}

.club-card.popular .club-type,
.club-card.popular .club-members {
  color: rgba(255,255,255,0.8);
}

.club-logo {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 12px;
}

.club-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-info h4 {
  margin: 0 0 8px;
  color: #303133;
  font-size: 16px;
}

.club-type {
  margin: 0 0 8px;
  color: #909399;
  font-size: 14px;
}

.club-description {
  margin: 0 0 12px;
  color: #606266;
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  line-clamp: 2; /* 标准属性，未来主流 */
}

.club-members,
.club-stats {
  margin: 0 0 12px;
  color: #909399;
  font-size: 14px;
}

.club-stats {
  display: flex;
  gap: 16px;
}

.club-stats span {
  display: flex;
  align-items: center;
  gap: 4px;
}

.club-actions {
  text-align: right;
}

.club-detail-dialog .el-dialog__body {
  padding: 20px;
}

.club-detail-logo {
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  margin: 0 auto;
}

.club-detail-logo img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.club-detail-info h3 {
  margin: 0 0 16px;
  color: #303133;
}

.club-detail-info p {
  margin: 8px 0;
  color: #606266;
}

.recruitments-section {
  margin-top: 24px;
}

.recruitments-section h4 {
  margin: 0 0 16px;
  color: #303133;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 8px;
}

.recruitment-item {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
}

.rec-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.rec-header h5 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.rec-content {
  margin-bottom: 16px;
}

.rec-content p {
  margin: 8px 0;
  color: #606266;
}

.rec-actions {
  text-align: right;
}

.debug-info {
  font-size: 12px;
  color: #606266;
  margin-top: 8px;
  padding: 4px;
  background-color: #f0f9ff;
  border-radius: 4px;
  text-align: left;
}

.pagination-container {
  margin-top: 24px;
  text-align: center;
}
</style>